<template>
  <div class="system-sysOrg-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-org-search mb15">
        <!--				<el-input size="default" placeholder="请输入部门名称" style="max-width: 180px"> </el-input>-->
        <!--				<el-button size="default" type="primary" class="ml10">-->
        <!--					<el-icon>-->
        <!--						<ele-Search />-->
        <!--					</el-icon>-->
        <!--					查询-->
        <!--				</el-button>-->
        <el-button size="default" type="success" class="ml10" @click="onOpenAddSysOrg('add',state.tableData.data)">
          <el-icon>
            <ele-FolderAdd/>
          </el-icon>
          新增组织机构
        </el-button>
      </div>
      <el-table
          :data="state.tableData.data"
          v-loading="state.tableData.loading"
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          max-height="calc(100vh - 200px)"
          stripe
          :expand-row-keys="state.expandedRowKeys"
          @expand-change="handleExpandChange"
      >
        <el-table-column prop="label" label="机构名称" show-overflow-tooltip width="480"></el-table-column>
        <el-table-column prop="orgType" label="机构类型" show-overflow-tooltip width="200">
          <template #default="scope">
            <el-tag>
              {{ orgTypeMap[scope.row.orgType].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="schoolType" label="学校类型" show-overflow-tooltip width="200">
          <template #default="scope">
            <el-tag v-if="scope.row.orgType==7&&scope.row.schoolType!=null">
              {{ schoolTypeMap[scope.row.schoolType].label }}
            </el-tag>
            <el-tag v-else>
              {{ schoolTypeMap[0].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="排序" show-overflow-tooltip width="80">
          <!--					<template #default="scope">-->
          <!--						{{ scope.$index }}-->
          <!--					</template>-->
        </el-table-column>
        <el-table-column prop="isDelete" label="状态" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isDelete==0">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="aliasClassName" label="机构别名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="gmtModified" label="修改时间" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作" show-overflow-tooltip width="140">
					<template #default="scope">
            <div v-if="scope.row.id!='1'">
<!--              <el-button size="small" text type="primary" @click="onOpenAddSysOrg('add',state.tableData.data)" :disabled="scope.row.isDelete === 1">新增</el-button>-->
              <el-button size="small" text type="primary" @click="onOpenEditSysOrg('edit', scope.row,state.tableData.data)" >修改</el-button>
              <el-button size="small" text type="primary" @click="onTableRowDel(scope.row)" :disabled="scope.row.isDelete === 1">删除</el-button>
            </div>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<sysOrgDialog ref="sysOrgDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="systemOrg">
import {defineAsyncComponent, ref, reactive, onMounted} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {systemApi} from "/@/api/system";
const {orgTree, removeById} = systemApi();
// 引入组件
const sysOrgDialog = defineAsyncComponent(() => import('/@/views/system/org/dialog.vue'));

// 定义变量内容
const sysOrgDialogRef = ref();
const state = reactive<SysOrgState>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 2100,
    },
  },
  expandedRowKeys: [], // 存储展开的行ID
});
// 定义机构类型映射对象
const orgTypeMap:TypeMap = {
  1: { label: '分类节点', description: 'NODES' },
  2: { label: '省、自治区、直辖市', description: 'PROVINCE' },
  3: { label: '地级市', description: 'CITY' },
  4: { label: '旗县区', description: 'DISTRICT' },
  5: { label: '教育局', description: 'BUREAU_EDUCATION' },
  6: { label: '教育局科室', description: 'BUREAU_EDUCATION_DEPARTMENT' },
  7: { label: '学校', description: 'SCHOOL' },
  8: { label: '学校科室', description: 'SCHOOL_DEPARTMENT' },
  9: { label: '教育阶段', description: 'EDUCATIONAL_STAGE' },
  10: { label: '年级', description: 'GRADE' },
  11: { label: '班级', description: 'CLASS' },
};
// 定义学校类型映射对象
const schoolTypeMap:TypeMap = {
  1: { label: '九年一贯制（小学+初中）', description: 'NINE_YEARS' },
  2: { label: '完全中学', description: 'COMPLETE' },
  3: { label: '六年制（小学）', description: 'SIZ_YEARS' },
  4: { label: '三年制（初中）', description: 'THEE_YEARS_MIDDLE' },
  5: { label: '三年制（高中）', description: 'THEE_YEARS_HIGH' },
  6: { label: '幼儿园', description: 'KINDERGARTEN' },
  7: { label: '特殊教育学校', description: 'SPECIAL_EDUCATION' },
  0: { label: '未知', description: '' },
};
// 初始化表格数据
const getTableData = async () => {
  state.tableData.loading = true;
  state.tableData.data = [];
  const res = await orgTree()
  if (res.status === 200) {
    state.tableData.data = res.data;
    state.tableData.loading = false;
  }
  state.tableData.total = state.tableData.data.length;
  // 恢复展开状态
  //state.expandedRowKeys = state.expandedRowKeys.filter(id => state.tableData.data.some(row => row.id === id));
};
// 打开新增菜单弹窗
const onOpenAddSysOrg = (type: string, tableData: OrgTreeType[]) => {
  sysOrgDialogRef.value.openDialog(type, null, tableData);
};
// 打开编辑菜单弹窗
const onOpenEditSysOrg = (type: string, row: OrgTreeType, tableData: OrgTreeType[]) => {
  sysOrgDialogRef.value.openDialog(type, row, tableData);
};
// 删除当前行



const onTableRowDel = (row: OrgTreeType) => {
	ElMessageBox.confirm(`此操作将删除该机构：${row.label}, 是否继续?`, '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then( async () => {
      const res = await removeById({id:row.id})
      //console.log(res)
      if (res.status === 200) {
        ElMessage.success('删除成功');
        await getTableData();
      } else {
        ElMessage.error('删除失败');
      }

    })
		.catch(() => {});
};
// 处理展开和折叠行事件
const handleExpandChange = (expandedRows: OrgTreeType, expanded:boolean ) => {
  if (expanded) {
    state.expandedRowKeys.push(expandedRows.id);
  } else {
    state.expandedRowKeys = state.expandedRowKeys.filter(id => id !== expandedRows.id);
  }
};
// 页面加载时
onMounted(() => {
  getTableData();
});
</script>
